package gitee.com.simonzhaojia.service;

import gitee.com.simonzhaojia.exception.GetImageUrlFailedException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class DownLoadTask implements Runnable{

  private String savePath;

  public DownLoadTask(String savePath) {
    this.savePath = savePath;
  }

  /**
   * 下载任务
   */
  @SneakyThrows
  @Override
  public void run() {
    log.info("Start downloading bing background image");
    log.info("savepath {}", savePath);
    Document document = Jsoup.connect("https://cn.bing.com/?bs_nt=1").get();
    Elements elements = document.head().select("link");
    List<String> urlList = elements.stream()
            .filter(e -> !e.getElementsByAttributeValueMatching("id", "bgLink").isEmpty())
            .map(element -> "https://cn.bing.com" + element.attr("href"))
            .collect(Collectors.toList());
    try {
      if (urlList.isEmpty()) {
        throw new GetImageUrlFailedException("Failed to get the image url");
      } else {
        for (String url : urlList) {
          downImage(url, savePath);
        }
      }
    } catch (GetImageUrlFailedException | IOException e) {
      log.info("Download failed");
    }
  }

  /**
   * 根据bing背景图片的URL下载图片
   *
   * @param imgurl   图片的URL地址
   * @param savePath 图片保存到计算机的路径
   * @throws IOException
   */
  public void downImage(String imgurl, String savePath) throws IOException {
    //使用OKhttp获取网络图片输入流
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().get().url(imgurl).build();
    Response response = client.newCall(request).execute();
    InputStream in = response.body().byteStream();

    Calendar now = Calendar.getInstance();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    String nowadays = format.format(now.getTime());

    // 创建文件
    File imgFile = new File(savePath + "bing-" + nowadays + ".jpeg");
    //创建输出流
    OutputStream out = new FileOutputStream(imgFile);
    int i = 0;
    while ((i = in.read()) != -1) {
      out.write(i);
    }
    in.close();
    out.close();
    log.info("Download successful");
  }
}
